import {request, useModel} from "@umijs/max";
import {ExposeParam, MdEditor} from "md-editor-rt";
import 'md-editor-rt/lib/style.css';
import '@vavt/rt-extension/lib/asset/style.css';
import VideoTool from "@/components/CustomEditor/VideoTool";
import {useRef} from "react";
import {createFromIconfontCN} from '@ant-design/icons'
import {Button, message} from "antd";

const IconFont = createFromIconfontCN()

export async function upload(
  data: FormData,
  options?: { [key: string]: any },
) {
  const hide = message.loading('上传中...', 0)
  const res = await request<{
    code: number;
    data: Record<string, any>;
    msg?: string;
  }>('/product-server/api/v1/file/upload', {
    method: 'POST',
    data,
    ...(options || {}),
  });
  hide()
  message.success("上传成功")
  return res
}

const CustomEditor = (props: any) => {
  const {initialState} = useModel('@@initialState');
  const editorRef = useRef<ExposeParam>();
  const onUploadImg = async (files: any[], callback: (arg0: any[]) => void) => {
    const res = await Promise.all(
      files.map((file: string | Blob) => {
        return new Promise((rev, rej) => {
          const form = new FormData();
          form.append('file', file);
          form.append('type', props.type || 'article');
          upload(form).then((res) => {
            res.data.name = ""
            return rev(res)
          })
            .catch((error) => rej(error));
        });
      })
    );

    // 方式一
    // callback(res.map((item) => item.data.url));
    // 方式二
    callback(
      res.map((item: any) => ({
        url: item.data.url,
        alt: item.data.name,
        title: item.data.name
      }))
    );
  };

  return <MdEditor
    // preview={false}
    ref={editorRef}
    placeholder='请输入文章内容！'
    onUploadImg={onUploadImg}
    onChange={props?.onChange}
    modelValue={props?.value || ''}
    theme={initialState?.settings?.navTheme === 'realDark' ? 'dark' : 'light'}
    language='zh-CN'
    toolbars={[
      0,
      'bold',
      'underline',
      'italic',
      '-',
      'strikeThrough',
      'sub',
      'sup',
      'quote',
      'unorderedList',
      'orderedList',
      'task',
      '-',
      // 'codeRow',
      // 'code',
      'link',
      'image',
      1,
      'table',
      // 'mermaid',
      // 'katex',
      '-',
      'revoke',
      'next',
      'save',
      '=',
      'pageFullscreen',
      'fullscreen',
      'preview',
      'previewOnly',
      'htmlPreview',
      // 'catalog',
      // 'github'
    ]}
    defToolbars={[
      <Button
        key={'title'}
        type={'text'}
        icon={<IconFont type={'icon-dabiaoti'}/>}
        onClick={() => {
          editorRef.current?.insert(() => {
            return {
              targetValue: `<center><h1 style="text-align: center;margin-top:40px;margin-bottom: 10px;">企业介绍</h1></center>\n`,
              select: true,
              deviationStart: 0,
              deviationEnd: 0
            };
          });
        }}
      />,
      <VideoTool key="mark-extension" onUploadSuccess={(videoUrl: any) => {
        editorRef.current?.insert(() => {
          /**
           * @return targetValue    待插入内容
           * @return select         插入后是否自动选中内容，默认：true
           * @return deviationStart 插入后选中内容鼠标开始位置，默认：0
           * @return deviationEnd   插入后选中内容鼠标结束位置，默认：0
           */
          return {
            targetValue: `<video width="100%" height="240" controls src="${videoUrl}"></video>\n`,
            select: true,
            deviationStart: 0,
            deviationEnd: 0
          };
        });
      }}/>,
    ]}
  />
}

export default CustomEditor
